package com.zx.notification.consumer.components;

import com.zx.core.wrapper.ObjectWrapper;
import com.zx.feign.client.SystemClient;
import com.zx.feign.client.dto.GetSysUserResponseDTO;
import com.zx.notification.common.dao.InboxReadRecordsMapper;
import com.zx.notification.common.enums.ReadStatusEnum;
import com.zx.notification.common.model.InboxReadRecords;
import com.zx.notification.common.utils.NotificationNoUtils;
import com.zx.notification.consumer.config.MailConfig;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

/**
 * 第三方通知组件
 * 用于调用真实的第三方服务，如短信、邮件、APP推送、微信等
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class ThirdPartyNotificationComponent {

    private final InboxReadRecordsMapper inboxReadRecordsMapper;
    private final JavaMailSender mailSender;
    private final SystemClient systemClient;
    private final MailConfig mailConfig;

    /**
     * 发送站内信
     *
     * @param notificationId 通知ID
     * @param title          消息标题
     * @param content        消息内容
     * @param userId         用户ID
     * @return ObjectWrapper 包含外部消息ID
     */
    public ObjectWrapper<String> sendInboxMessage(String notificationId, String title, String content, String userId) {
        ObjectWrapper<String> result = new ObjectWrapper<>();
        try {
            log.info("发送站内信给用户{}: 标题={}, 内容={}", userId, title, content);

            // 创建站内信阅读记录
            InboxReadRecords record = new InboxReadRecords();
            record.setId(NotificationNoUtils.generateNotificationId());
            record.setNotificationId(notificationId);
            record.setUserId(userId);
            // 初始状态为未读
            record.setReadStatus(ReadStatusEnum.UNREAD.getCode());
            record.setCreateTime(LocalDateTime.now());
            record.setUpdateTime(LocalDateTime.now());

            // 插入到数据库
            int insertResult = inboxReadRecordsMapper.insert(record);

            if (insertResult > 0) {
                log.info("站内信发送成功，通知ID: {}, 用户ID: {}, 记录ID: {}", notificationId, userId, record.getId());
                result.setData(record.getId());
            } else {
                result.fail("站内信发送失败，无法创建阅读记录");
            }
        } catch (Exception e) {
            log.error("发送站内信异常，通知ID: {}, 用户ID: {}", notificationId, userId, e);
            result.fail("站内信发送异常: " + e.getMessage());
        }
        return result;
    }

    /**
     * 发送邮件
     *
     * @param userId  用户ID
     * @param content 邮件内容
     * @return ObjectWrapper 包含外部消息ID
     */
    public ObjectWrapper<String> sendEmail(String userId, String content) {
        ObjectWrapper<String> result = new ObjectWrapper<>();
        try {
            // 获取用户邮箱地址
            ObjectWrapper<GetSysUserResponseDTO> userWrapper = systemClient.getUserInfoById(userId);
            if (null == userWrapper || null == userWrapper.getData()) {
                result.fail("无法获取用户信息，userId: " + userId);
                return result;
            }

            String userEmail = userWrapper.getData().email();
            if (null == userEmail || userEmail.isEmpty()) {
                result.fail("用户邮箱地址为空，userId: " + userId);
                return result;
            }

            // 发送邮件
            SimpleMailMessage message = new SimpleMailMessage();
            message.setTo(userEmail);
            message.setSubject("系统通知");
            message.setText(content);

            // 从配置中获取发件人
            message.setFrom(mailConfig.getFrom());

            mailSender.send(message);

            log.info("邮件发送成功，收件人: {}, 内容: {}", userEmail, content);

        } catch (Exception e) {
            log.error("发送邮件失败，用户ID: {}, 内容: {}", userId, content, e);
            result.fail("邮件发送失败: " + e.getMessage());
        }
        return result;
    }

    /**
     * 发送短信
     *
     * @param userId  用户ID
     * @param content 短信内容
     * @return ObjectWrapper 包含外部消息ID
     */
    public ObjectWrapper<String> sendSms(String userId, String content) {
        ObjectWrapper<String> result = new ObjectWrapper<>();
        try {
            // TODO: 由于没有短信环境，暂时使用TODO处理
            log.warn("短信消息处理功能尚未实现: 用户ID={}, 内容={}", userId, content);

            // 临时返回模拟的外部消息ID
            String externalMsgId = "SMS_" + java.util.UUID.randomUUID().toString().replace("-", "").toUpperCase();
            log.info("短信发送成功，外部消息ID: {}", externalMsgId);

            result.setData(externalMsgId);
        } catch (Exception e) {
            log.error("发送短信异常，用户ID: {}, 内容: {}", userId, content, e);
            result.fail("短信发送异常: " + e.getMessage());
        }
        return result;
    }

    /**
     * 发送APP推送
     *
     * @param userId  用户ID
     * @param content 推送内容
     * @return ObjectWrapper 包含外部消息ID
     */
    public ObjectWrapper<String> sendAppPush(String userId, String content) {
        ObjectWrapper<String> result = new ObjectWrapper<>();
        try {
            // TODO: 由于没有APP推送环境，暂时使用TODO处理
            log.warn("APP推送消息处理功能尚未实现: 用户ID={}, 内容={}", userId, content);

            // 临时返回模拟的外部消息ID
            String externalMsgId = "APP_" + java.util.UUID.randomUUID().toString().replace("-", "").toUpperCase();
            log.info("APP推送发送成功，外部消息ID: {}", externalMsgId);

            result.setData(externalMsgId);
        } catch (Exception e) {
            log.error("发送APP推送异常，用户ID: {}, 内容: {}", userId, content, e);
            result.fail("APP推送发送异常: " + e.getMessage());
        }
        return result;
    }

    /**
     * 发送微信消息
     *
     * @param userId  用户ID
     * @param content 微信消息内容
     * @return ObjectWrapper 包含外部消息ID
     */
    public ObjectWrapper<String> sendWechatMessage(String userId, String content) {
        ObjectWrapper<String> result = new ObjectWrapper<>();
        try {
            // TODO: 由于没有微信环境，暂时使用TODO处理
            log.warn("微信消息处理功能尚未实现: 用户ID={}, 内容={}", userId, content);

            // 临时返回模拟的外部消息ID
            String externalMsgId = "WX_" + java.util.UUID.randomUUID().toString().replace("-", "").toUpperCase();
            log.info("微信消息发送成功，外部消息ID: {}", externalMsgId);

            result.setData(externalMsgId);
        } catch (Exception e) {
            log.error("发送微信消息异常，用户ID: {}, 内容: {}", userId, content, e);
            result.fail("微信消息发送异常: " + e.getMessage());
        }
        return result;
    }

    /**
     * 通过WebSocket发送消息
     *
     * @param sessionId WebSocket会话ID
     * @param content   消息内容
     * @return ObjectWrapper 包含外部消息ID
     */
    public ObjectWrapper<String> sendWebSocketMessage(String sessionId, String content) {
        ObjectWrapper<String> result = new ObjectWrapper<>();
        try {
            // TODO: WebSocket消息发送需要依赖concept-websocket-loadbalance-spring-boot-starter或其他WebSocket管理机制
            log.warn("WebSocket消息发送功能尚未实现: 会话ID={}, 内容={}", sessionId, content);

            // 临时记录日志表示发送成功
            log.info("WebSocket消息发送成功");

            // 返回模拟的外部消息ID
            String externalMsgId = "WS_" + java.util.UUID.randomUUID().toString().replace("-", "").toUpperCase();
            result.setData(externalMsgId);
        } catch (Exception e) {
            log.error("WebSocket消息发送异常，会话ID: {}, 内容: {}", sessionId, content, e);
            result.fail("WebSocket消息发送异常: " + e.getMessage());
        }
        return result;
    }
}